package com.itheima.advice;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.MyThreadLocalUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/*
 *
 * 这个类承载着我们如何对已有的业务功能进行增强的逻辑
 *
 * */
@Aspect
@Component
public class MyAspectLog {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("execution(* com.itheima.service.*.*(..))")
    public void pt() {
    }

    @Around("pt()")
    public Object totalTime(ProceedingJoinPoint pjp) throws Throwable {
        String name = pjp.getSignature().getName();
        if ("login".equals(name)) {
            Object o = pjp.proceed();
            return o;
        }

        long t1 = System.currentTimeMillis();
        Object o = null;
        try {
            o = pjp.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            long t2 = System.currentTimeMillis();
            long l = t2 - t1;
            Map<String, Object> map = MyThreadLocalUtils.getValue();
            Integer userId = Integer.parseInt(map.get("id").toString());
            OperateLog log = OperateLog.builder()
                    .operateUser(userId)
                    .operateTime(LocalDateTime.now())
                    .className(pjp.getSignature().getDeclaringTypeName())
                    .methodName(name)
                    .methodParams(pjp.getArgs().toString())
                    .returnValue(o != null ? o.toString() : "无返回值")
                    .costTime(l)
                    .build();
            //记录日志
            operateLogMapper.insert(log);
        }
        return o;
    }
}
